package com.example.timeemail;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import android.Manifest;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.TextView;
import android.widget.Toast;

import com.example.timeemail.utils.LoginResult;
import com.example.timeemail.utils.OkHttpUtil;
import com.google.gson.Gson;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Response;

public class SigninActivity extends AppCompatActivity {

    private EditText EdtUsername;
    private EditText EdtPassWord;
    private CheckBox Cbrme;

    //读写权限
    private static String[] PERMISSIONS_STORAGE = {
            Manifest.permission.READ_EXTERNAL_STORAGE,
            Manifest.permission.WRITE_EXTERNAL_STORAGE,
            Manifest.permission.INTERNET};
    //请求状态码
    private static int REQUEST_PERMISSION_CODE = 1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_signin);
        if (android.os.Build.VERSION.SDK_INT > 9) {
            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
        }

        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_PERMISSION_CODE);
            }
            if (ActivityCompat.checkSelfPermission(this, Manifest.permission.INTERNET) != PackageManager.PERMISSION_GRANTED) {
                ActivityCompat.requestPermissions(this, PERMISSIONS_STORAGE, REQUEST_PERMISSION_CODE);
            }
        }

        SharedPreferences sharedPreferences = this.getSharedPreferences("loginData", MODE_PRIVATE);
        String username = sharedPreferences.getString("username", null);
        String password = sharedPreferences.getString("userpassword", null);

/*        System.out.println(username);

        if (username != null && password != null) {
            Intent intent = new Intent(SigninActivity.this,MainActivity.class);
            intent.putExtra("login","登陆成功");
            startActivity(intent);
        }*/
        EdtUsername = (EditText) findViewById(R.id.et_signin_id);
        EdtPassWord = (EditText) findViewById(R.id.et_signin_password);
        Cbrme = (CheckBox) findViewById(R.id.Cbrme);

        EdtUsername.setText(username);
        EdtPassWord.setText(password);

    }

    public void btn_register_submit(View view) {
        Intent intent = new Intent(SigninActivity.this,RegisterActivity.class);
        startActivity(intent);
    }

    public void btn_submit_signin_onclick(View view) {

        RadioButton RbtnUserLogin = (RadioButton) findViewById(R.id.RbtnUserLogin);

        if (RbtnUserLogin.isChecked()) {
            String userName = EdtUsername.getText().toString();
            String loginPassword = EdtPassWord.getText().toString();
            loginWithOkHttp(userName, null, loginPassword);
        }else {
            String email = EdtUsername.getText().toString();
            String loginPassword = EdtPassWord.getText().toString();
            loginWithOkHttp(null, email, loginPassword);
        }
    }

    //实现登陆
    private void loginWithOkHttp(String account, String email, String password) {
        OkHttpUtil.loginWithOkHttp(account, email, password, new okhttp3.Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("MianActivity","登陆请求失败:" + e.getLocalizedMessage());
                ToastShow("登陆请求失败：" + e.getLocalizedMessage());
            }

            //请求成功，获取服务器返回数据
            @Override
            public void onResponse(Call call, Response response) throws IOException {
                //获取返回内容
                final String responseData = response.body().string();
                //在主线程更新ui和响应用户操作
                runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        LoginResult result = new Gson().fromJson(responseData, LoginResult.class);
                        if (result.getStatus().equals("200")) {
                            ToastShow("登陆成功");
                            SharedPreferences sharedPreferences = getSharedPreferences("loginData",MODE_PRIVATE);
                            SharedPreferences.Editor editor = sharedPreferences.edit();
                            RadioButton RbtnUserLogin = (RadioButton) findViewById(R.id.RbtnUserLogin);
                            if (RbtnUserLogin.isChecked()) {
                                editor.putString("username",EdtUsername.getText().toString());
                            }else{
                                editor.putString("email",EdtUsername.getText().toString());
                            }

                            editor.putString("userpassword",EdtPassWord.getText().toString());
                            editor.commit();
                            Intent intent = new Intent(SigninActivity.this,MainActivity.class);
                            intent.putExtra("login","登陆成功");
                            startActivity(intent);
                        } else {
                            Toast.makeText(SigninActivity.this,result.getMsg(),Toast.LENGTH_SHORT).show();
                        }
                    }
                });
            }
        });
    }

    void ToastShow(String context) {
        Toast toast = Toast.makeText(this, context, Toast.LENGTH_LONG);
        View view = LayoutInflater.from(this).inflate(R.layout.toast_template, null);
        TextView TxtTaostContext = (TextView) view.findViewById(R.id.TxtTaostContext);
        TxtTaostContext.setText(context);
        toast.setView(view);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        if (requestCode == REQUEST_PERMISSION_CODE) {
            for (int i = 0; i < permissions.length; i++) {
                Log.i("MainActivity", "申请的权限为：" + permissions[i] + ",申请结果：" + grantResults[i]);
            }
        }
    }

}